#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:

'''covert many excel files Without money to one word file
'''

__revision__ = '0.1'
__author__ = 'lxd'

import win32com.client
from win32com.client import Dispatch, constants
import tools
import word, excel
import formatTable
import traceback
import time

class ExcelToWord(object):
    def __init__(self, excelNames, wordName):
        self.excel = excel.Excel(False)
        self.excelNames = tools.findExcels(excelNames)

        self.word = word.Word()
        self.word.open(wordName)

    def process(self):
        o_time = time.time()
        for excelName in self.excelNames:
            name = tools.getFileName(excelName)
            old_time = time.time()
            print 'coverting', name
            self.word.insertWordAndSetStyle(name, u'dt_2级标题')
            self.word.nextLine(2)

            self.excel.open(excelName)
            for sheet in self.excel.getSheets():
                if sheet.Visible:#only process visible sheet
                    sheet.Select()
                    self.processExcel()
                    self.processWord()
            self.excel.close()

            #self.word.save()
            print time.time()-old_time

        self.excel.quit()
        print 'covert is over'
        print time.time()-o_time

    def processExcel(self):
        self.subTitles = self.excel.getSubTitles()
        self.title = self.excel.getTitle()
        self.excel.copyWithoutMoney()

    def processWord(self):
        self.word.nextLine()

        self.word.insertWordAndSetStyle(self.title, u'dt_图表名')
        self.word.nextLine()

        self.word.paste()

        pos_after_table = self.word.getMousePos()

        self.word.getTable()
        fTable = formatTable.FormatTable(self.word)
        fTable.setTableStyle()
        fTable.delBlankRows()

        self.word.getTable()
        for index, subTitle in self.subTitles:
            self.word.insertMergeRowWithTitle(index, subTitle)
            self.word.setSubTitleStyle(index)

        pos_after_table += 1000

        self.word.setMousePos(pos_after_table)

if __name__ == '__main__':
    #excelNames = [u'c:\\users\\lxd\\desktop\\test\\汇总.xls',
                #u'c:\\users\\lxd\\desktop\\test\\文档',]
    #excelNames = [r'c:\users\lxd\desktop\1.xls']
    excelNames = [r'c:\users\lxd\desktop\1.xls']
    wordName = r'c:\users\lxd\desktop\1.doc'
    e = ExcelToWord(excelNames, wordName)
    e.process()
    #try:
    #except Exception, ex:
        #traceback.print_exc(file = open('error.txt', 'a'))

